# _*_ coding: utf-8 _*_
from odoo import models, fields, api
from odoo.exceptions import UserError


class StockPutOnShelf(models.Model):
    _name = "stock.put.on.shelf"
    _inherit = "mail.thread"
    _description = "库存上架"
    _order = "name desc"

    name = fields.Char(string=u"单号", required=True, index=True, copy=False, default='/', readonly=True)
    user_id = fields.Many2one("res.users", string=u"上架人", default=lambda self: self.env.user, readonly=True)
    date = fields.Date(string=u"上架日期", readonly=True)
    description = fields.Char(string=u"备注")
    line_ids = fields.One2many("stock.put.on.shelf.line", "shelf_id", string=u"明细行")
    state = fields.Selection([
        ("draft", "草稿"),
        ("committed", "已提交"),
        ("done", "完成"),
    ], default="draft", copy=False)
    move_ids = fields.One2many("stock.move", "shelf_id")
    move_count = fields.Integer(compute="_compute_move_count")

    @api.depends("move_ids")
    def _compute_move_count(self):
        for shelf in self:
            shelf.move_count = len(shelf.move_ids)

    @api.model
    def create(self, vals):
        if vals.get('name', '/') == '/':
            vals['name'] = self.env['ir.sequence'].next_by_code('stock.put.on.shelf') or '/'
        return super(StockPutOnShelf, self).create(vals)

    @api.multi
    def unlink(self):
        if self.filtered(lambda shelf: shelf.state != "draft"):
            raise UserError(u"只能删除草稿状态的上架单据")
        return super(StockPutOnShelf, self).unlink()

    def action_commit(self):
        self.ensure_one()
        if not self.state == "draft":
            return
        self.state = "committed"

    def action_done(self):
        for order in self:
            if order.state == "done":
                continue
            if not order.line_ids:
                raise UserError("请先录入明细。")
            moves = self.env['stock.move']
            for line in order.line_ids:
                move = line.create_move()
                moves += move
                if move.product_id.type == 'product':
                    quants = self.env['stock.quant'].quants_get_preferred_domain(
                        move.product_qty, move,
                        domain=[
                            ('qty', '>', 0),
                            ('lot_id', '=', line.lot_id.id)
                        ])
                    if any([not x[0] for x in quants]):
                        raise UserError('没有足够库存')
                    self.env['stock.quant'].quants_reserve(quants, move)
                move.action_done()
            moves.recalculate_move_state()
            order.move_ids = moves
            order.state = "done"
            order.date = fields.Date.today()

    def action_reset(self):
        self.filtered(lambda order: order.state == "committed").write({"state": "draft"})

    @api.multi
    def action_get_stock_move(self):
        action = self.env.ref('stock.stock_move_action').read([])[0]
        action['domain'] = [('id', 'in', self.move_ids.ids)]
        return action
